#include "pch.h"
#include "DatabaseDataProvider.hpp"




DatabaseDataProvider::DatabaseDataProvider(db::Connection::Ptr connection, db::TableDL::const_Ptr table)
	: m_connection(connection)
	, m_table(table)
	, m_lastId(0)
	, m_batchSize(1000)
{
	verify(connection->isOpen());
	verify(table->exists(connection));
}
///////////////////////////////////////////////////////////////////////////////////////////////////

DatabaseDataProvider::~DatabaseDataProvider()
{}
///////////////////////////////////////////////////////////////////////////////////////////////////




Reply::Opt DatabaseDataProvider::next()
{
	if(m_replies.size() == 0)
	{
		QSqlQuery query = m_connection->prepare(QString("SELECT id, url, data FROM %1 WHERE id >= :id LIMIT 0, :limit").arg(m_table->dbName()));
		query.bindValue(":id", m_lastId);
		query.bindValue(":limit", m_batchSize);

		if(!query.exec())
			// TODO: Note the error
			return Reply::Opt();

		while(query.next())
		{
			QVariant     variant;
			QUrl         url;
			QByteArray   data;

			variant = query.value(0);
			if(!variant.canConvert(QVariant::ULongLong))
				// TODO: Note the error
				continue;
			m_lastId = variant.toULongLong();

			variant = query.value(1);
			if(!variant.canConvert(QVariant::String))
				// TODO: Note the error
				continue;

			url = variant.toString();
			if(!url.isValid())
				// TODO: Note the error
				continue;

			variant = query.value(2);
			if(!variant.canConvert(QVariant::ByteArray))
				// TODO: Note the error
				continue;

			data = variant.toByteArray();
			if(data.isNull())
				// TODO: Note the error
				continue;

			m_replies << Reply(url, data);
		}
	}

	if(m_replies.size())
	{
		Reply reply = m_replies.front();
		m_replies.pop_front();
		return reply;
	}
	else
	{
		return Reply::Opt();
	}
}
///////////////////////////////////////////////////////////////////////////////////////////////////

void DatabaseDataProvider::insert(const Reply& reply)
{
	QByteArray escapedData = reply.content();
	escapedData.replace("'", "\\'");

	QSqlQuery query = m_connection->prepare(QString("INSERT INTO %1 (url, data) VALUES (:url, :data)").arg(m_table->dbName()));
	query.bindValue(":url", reply.url().toString());
	query.bindValue(":data", reply.content());
	if(!query.exec())
		// TODO: Log this
		return;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
